import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

/**
 * 通用的分页/筛选与路由 query 同步
 * 约定路由参数：p(页码) s(每页) c(分类) t(标签) q(关键字) o(排序) d(时间窗)
 */
export function usePageQuery(initial?: Partial<{
  pageNo: number
  pageSize: number
  categoryId?: number
  tagId?: number
  keyword?: string
  sortBy?: 'latest' | 'views' | 'likes' | 'comments'
  sinceDays?: number
}>) {
  const route = useRoute()
  const router = useRouter()

  const pageNo = ref<number>(Number(route.query.p) > 0 ? Number(route.query.p) : (initial?.pageNo ?? 1))
  const pageSize = ref<number>(Number(route.query.s) > 0 ? Number(route.query.s) : (initial?.pageSize ?? 12))
  const categoryId = ref<number | undefined>(Number(route.query.c) > 0 ? Number(route.query.c) : initial?.categoryId)
  const tagId = ref<number | undefined>(Number(route.query.t) > 0 ? Number(route.query.t) : initial?.tagId)
  const keyword = ref<string>(typeof route.query.q === 'string' ? route.query.q : (initial?.keyword ?? ''))
  const sortBy = ref<'latest' | 'views' | 'likes' | 'comments'>(
    typeof route.query.o === 'string' && ['latest', 'views', 'likes', 'comments'].includes(route.query.o) ? (route.query.o as any) : (initial?.sortBy ?? 'latest')
  )
  const sinceDays = ref<number>(route.query.d != null && !isNaN(Number(route.query.d)) ? Number(route.query.d) : (initial?.sinceDays ?? 30))

  function pushQuery() {
    router.replace({
      name: route.name as string,
      query: {
        p: String(pageNo.value),
        s: String(pageSize.value),
        c: categoryId.value,
        t: tagId.value,
        q: keyword.value || undefined,
        o: sortBy.value,
        d: sinceDays.value
      } as any
    })
  }

  return { pageNo, pageSize, categoryId, tagId, keyword, sortBy, sinceDays, pushQuery }
}


